package com.pig4cloud.pig.djjk.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.pig4cloud.pig.common.security.annotation.Inner;
import com.pig4cloud.pig.djjk.domain.vo.AjaxResult;
import com.pig4cloud.pig.djjk.service.DispatchService;
import com.pig4cloud.pig.djjk.service.sence.AisService;
import com.wd.ais.domain.dto.AisEventReceiver;
import com.wd.ais.domain.dto.AisEventUnsubResponse;
import com.wd.ais.domain.dto.AisEventsListResponse;
import com.wd.ais.service.AisPortraitsServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @className: DeviceController
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2023/6/3
 **/
@RestController
@RequestMapping("/ais")
@Inner(value = false)
public class SenseEventController {
    Logger log = LoggerFactory.getLogger(SenseEventController.class);
    @Autowired
    ApplicationEventPublisher applicationEventPublisher;

    @Autowired
	AisService aisService;

    @Autowired
	DispatchService dispatchService;

    @Resource(name = "aisPortraitsService1")
    AisPortraitsServiceImpl portraitsService1;

	@Inner(value = false)
	@RequestMapping("/event/receiver")
	@ResponseBody
	public AjaxResult eventServer1(@RequestBody JSONObject eventBody) {
		String receiveStr = eventBody.toString();
		log.info(receiveStr);
		AisEventReceiver response = JSON.parseObject(receiveStr, new TypeReference<AisEventReceiver>() { });
		String recordType = response.getRecordType();

		if (StrUtil.equals(recordType, "portrait_stranger")) {//pedestrian_capture   portrait_stranger
			log.info("ais push event");
			dispatchService.aisToFaceLibSearch(response);
		}
		return AjaxResult.success();
	}

//	@Inner(value = false)
//    @RequestMapping("/event/receiver")
//    @ResponseBody
//    public AjaxResult eventServer1(@RequestBody JSONObject eventBody) {
//        String receiveStr = eventBody.toString();
//        log.info(receiveStr);
//        AisEventReceiver response = JSON.parseObject(receiveStr, new TypeReference<AisEventReceiver>() { });
//        String recordType = response.getRecordType();
//
//        if (StrUtil.equals(recordType, "portrait_stranger")) {//pedestrian_capture   portrait_stranger
//            log.info("ais push event");
//            dispatchService.aisToFaceLibSearch(response);
////            applicationEventPublisher.publishEvent(new AttentionDiscoverEvent(this, response));
//        }else if (StrUtil.equals(recordType, "portrait_normal")) {//pedestrian_capture   portrait_stranger
//            log.info("ais push event");
//            dispatchService.distinctHandler(response);
////            applicationEventPublisher.publishEvent(new AttentionDiscoverEvent(this, response));
//        }
//        return AjaxResult.success();
////        {"serialNumber":"0470dce4-03a0-4b82-891e-ae4645648e9d","objectId":"257eded7-8f89-11ef-e814-02c57800f944","eventId":"","dataType":"OBJECT_FACE","recordType":"portrait_stranger","platformType":"LOCAL","portraitImage":{"url":"video_face_cropped/20241021-084747a40-089f4b81ff9371-00000000-00001c34"},"panoramicImage":{"url":"video_face_panoramic/20241021-084747a43-089f4a9a5b17f0-00000000-0004aee9"},"capturedTime":1729500467432,"receivedTime":1729500467432,"createTime":1729500467475,"viewInfo":{"viewed":0,"confirmed":0},"score":0.049258742,"deviceInfo":{"device":{"identifierId":"0240406196255258324992","deviceName":"A区待访等候大厅17","deviceCode":"C57","platformIdentifierId":"118384891302982070272","platformType":"LOCAL","deviceType":"CAMERA","position":"[206.22297697283796,470.2252150711237]","rtspAddress":"rtsp://admin:Admin@123@18.18.10.57","rtspDeputyAddress":""},"deviceGroup":{"identifierId":"0240407278921659461632","name":"信访大厅","mapUrl":"OTHER/20241014-054638a10-05784ca41c7b17-00000000-0001d3ef","mapWidth":2047,"mapHeight":1240}},"taskInfo":{"task":{"taskId":"12024101415014875091","taskName":"人脸识别-A区待访等候大厅17-8573ee343","taskType":"portrait","detectType":"portrait_tailing"},"roi":{"ruleId":"320faf6f595c4d6a96356bd442dd7198","roiNum":"","roiName":"","verticeList":[{"x":0,"y":0},{"x":1,"y":0},{"x":1,"y":1},{"x":0,"y":1},{"x":0,"y":0}]}},"stackeds":[{"width":48,"top":468,"left":702,"height":48}],"attrs":{"age_lower_limit":{"value":"24","score":1},"age_up_limit":{"value":"34","score":1},"respirator_color":{"value":"COLOR_TYPE_WITHOUT","score":0.99994475},"st_respirator":{"value":"ST_RESPIRATOR_WITHOUT","score":0.9998751},"glass_style":{"value":"GLASSES_STYLE_TYPE_WITHOUT","score":0.9864539},"st_age_value":{"value":"29","score":1},"st_bang_style":{"value":"ST_BANG_STYLE_TYPE_WITHOUT","score":0.9999386},"gender_code":{"value":"FEMALE","score":0.99860054},"st_age":{"value":"ST_ADULT","score":1},"cap_style":{"value":"HAT_STYLE_TYPE_WITHOUT","score":0.99999815},"st_helmet_style":{"value":"ST_HELMET_STYLE_TYPE_WITHOUT","score":0.99951714},"mustache_style":{"value":"MUSTACHE_STYLE_TYPE_WITHOUT","score":0.9999837},"st_headphone_style":{"value":"ST_HEADPHONE_STYLE_TYPE_WITHOUT","score":0.99988294}},"particular":{"score":0.049258742,"mask":"NONE","helmet":"NONE","associationId":"","portraitDb":{"portraitDbId":60003,"identifierId":"069368214133012967424","libId":"27b03a80-75f0-4863-8316-c9a73cef0000","libImportType":"WEB","featureDbId":"27b03a80-75f0-4863-8316-c9a73cef0000","type":1,"name":"工作人员"},"portrait":{"portraitId":60006,"identifierId":"085392572101984530432","identity":"f1beLclhJHsG1Mgsh7wkGQ==","name":"杨玉","aliasName":"","gender":"3","company":"","dept":"","employeeNumber":"","address":"","phone":"","vehiclePlateNumber":"","enableState":1,"activeState":2,"activationTime":1725292800000,"expirationTime":0,"picUrl":"GLOBAL/20240903-165404a2-3b1f59dc0647-00000000-00004402","avatarShow":"","type":1,"idNumber":"","pin":"","prompt":"","position":"","birthday":"","remark":"","createTime":1725378419923,"featureKey":"d57609a3fb2549bfaf084ae8191dee90","orgId":-2,"orgName":"默认组织"},"trackEvent":"END"},"applet":"{\"type\":1,\"face\":{\"quality\":0.41434717,\"rectangle\":{\"vertices\":[{\"x\":36,\"y\":36},{\"x\":84,\"y\":84}]},\"track_id\":200085463,\"landmarks\":[{\"x\":31,\"y\":58},{\"x\":32,\"y\":62},{\"x\":33,\"y\":66},{\"x\":35,\"y\":69},{\"x\":36,\"y\":73},{\"x\":38,\"y\":77},{\"x\":41,\"y\":80},{\"x\":44,\"y\":83},{\"x\":47,\"y\":86},{\"x\":51,\"y\":88},{\"x\":54,\"y\":89},{\"x\":58,\"y\":90},{\"x\":62,\"y\":91},{\"x\":66,\"y\":91},{\"x\":71,\"y\":91},{\"x\":74,\"y\":90},{\"x\":78,\"y\":88},{\"x\":80,\"y\":86},{\"x\":81,\"y\":83},{\"x\":81,\"y\":80},{\"x\":81,\"y\":78},{\"x\":82,\"y\":75},{\"x\":82,\"y\":72},{\"x\":82,\"y\":69},{\"x\":83,\"y\":66},{\"x\":83,\"y\":63},{\"x\":83,\"y\":60},{\"x\":83,\"y\":57},{\"x\":82,\"y\":54},{\"x\":81,\"y\":51},{\"x\":81,\"y\":49},{\"x\":80,\"y\":46},{\"x\":79,\"y\":43},{\"x\":51,\"y\":49},{\"x\":54,\"y\":45},{\"x\":58,\"y\":43},{\"x\":63,\"y\":42},{\"x\":67,\"y\":42},{\"x\":73,\"y\":40},{\"x\":75,\"y\":38},{\"x\":76,\"y\":37},{\"x\":77,\"y\":36},{\"x\":79,\"y\":37},{\"x\":73,\"y\":49},{\"x\":75,\"y\":53},{\"x\":77,\"y\":56},{\"x\":80,\"y\":60},{\"x\":72,\"y\":66},{\"x\":74,\"y\":66},{\"x\":77,\"y\":65},{\"x\":80,\"y\":64},{\"x\":81,\"y\":62},{\"x\":56,\"y\":55},{\"x\":59,\"y\":55},{\"x\":63,\"y\":53},{\"x\":65,\"y\":53},{\"x\":63,\"y\":54},{\"x\":58,\"y\":56},{\"x\":75,\"y\":48},{\"x\":76,\"y\":47},{\"x\":78,\"y\":46},{\"x\":79,\"y\":45},{\"x\":78,\"y\":47},{\"x\":76,\"y\":48},{\"x\":55,\"y\":47},{\"x\":59,\"y\":46},{\"x\":63,\"y\":45},{\"x\":67,\"y\":44},{\"x\":74,\"y\":42},{\"x\":75,\"y\":40},{\"x\":76,\"y\":39},{\"x\":78,\"y\":38},{\"x\":61,\"y\":54},{\"x\":61,\"y\":55},{\"x\":61,\"y\":54},{\"x\":77,\"y\":46},{\"x\":77,\"y\":47},{\"x\":77,\"y\":47},{\"x\":69,\"y\":51},{\"x\":74,\"y\":48},{\"x\":70,\"y\":61},{\"x\":80,\"y\":57},{\"x\":69,\"y\":65},{\"x\":82,\"y\":60},{\"x\":68,\"y\":77},{\"x\":73,\"y\":73},{\"x\":77,\"y\":71},{\"x\":79,\"y\":70},{\"x\":80,\"y\":70},{\"x\":81,\"y\":70},{\"x\":80,\"y\":72},{\"x\":80,\"y\":74},{\"x\":80,\"y\":76},{\"x\":79,\"y\":78},{\"x\":75,\"y\":78},{\"x\":72,\"y\":78},{\"x\":69,\"y\":76},{\"x\":74,\"y\":74},{\"x\":79,\"y\":72},{\"x\":79,\"y\":72},{\"x\":80,\"y\":72},{\"x\":79,\"y\":73},{\"x\":78,\"y\":74},{\"x\":74,\"y\":76},{\"x\":61,\"y\":54},{\"x\":77,\"y\":47}],\"attributes\":{\"age_lower_limit\":\"24\",\"age_up_limit\":\"34\",\"cap_style\":\"hat_style_type_without\",\"gender_code\":\"female\",\"glass_style\":\"glasses_style_type_without\",\"mustache_style\":\"mustache_style_type_without\",\"respirator_color\":\"color_type_without\",\"st_age\":\"st_adult\",\"st_age_value\":\"29\",\"st_bang_style\":\"st_bang_style_type_without\",\"st_headphone_style\":\"st_headphone_style_type_without\",\"st_helmet_style\":\"st_helmet_style_type_without\",\"st_respirator\":\"st_respirator_without\"},\"attributes_with_score\":{\"age_lower_limit\":{\"type\":1,\"category\":\"age_lower_limit\",\"value\":24},\"age_up_limit\":{\"type\":1,\"category\":\"age_up_limit\",\"value\":34},\"cap_style\":{\"type\":2,\"category\":\"hat_style_type_without\",\"value\":0.99999815},\"gender_code\":{\"type\":2,\"category\":\"female\",\"value\":0.99860054},\"glass_style\":{\"type\":2,\"category\":\"glasses_style_type_without\",\"value\":0.9864539},\"mustache_style\":{\"type\":2,\"category\":\"mustache_style_type_without\",\"value\":0.9999837},\"respirator_color\":{\"type\":2,\"category\":\"color_type_without\",\"value\":0.99994475},\"st_age\":{\"type\":2,\"category\":\"st_adult\",\"value\":1},\"st_age_value\":{\"type\":1,\"category\":\"st_age_value\",\"value\":29},\"st_bang_style\":{\"type\":2,\"category\":\"st_bang_style_type_without\",\"value\":0.9999386},\"st_headphone_style\":{\"type\":2,\"category\":\"st_headphone_style_type_without\",\"value\":0.99988294},\"st_helmet_style\":{\"type\":2,\"category\":\"st_helmet_style_type_without\",\"value\":0.99951714},\"st_respirator\":{\"type\":2,\"category\":\"st_respirator_without\",\"value\":0.9998751}},\"face_score\":0.41434717},\"portrait_image_location\":{\"panoramic_image_size\":{\"width\":1920,\"height\":1080},\"portrait_image_in_panoramic\":{\"vertices\":[{\"x\":666,\"y\":432},{\"x\":786,\"y\":552}]},\"portrait_in_panoramic\":{\"vertices\":[{\"x\":702,\"y\":468},{\"x\":750,\"y\":516}]}},\"object_id\":\"257eded7-8f89-11ef-e814-02c57800f944\",\"algo\":{\"app_name\":\"com.sensetime.algo.facepedestrian.v2.replica2\",\"app_version\":10011,\"object_type\":\"default\",\"data\":{\"type_url\":\"annotation.json#/definitions/default_v0\",\"value\":\"{}\"}}}"}
//    }

    @RequestMapping("/subEvent1")
	@Inner(value = false)
    @ResponseBody
    public AjaxResult subEvent(String url){
        aisService.eventsSub1(url);
        return AjaxResult.success();
    }


    @RequestMapping("/listEvent1")
	@Inner(value = false)
    @ResponseBody
    public AjaxResult listEvent1(){
        AisEventsListResponse response =  aisService.listEvent1();
        return AjaxResult.success(response);
    }


    @RequestMapping("/unsubEvent1")
	@Inner(value = false)
    @ResponseBody
    public AjaxResult unsubEvent1(String url){
        AisEventUnsubResponse response =  aisService.unsubEvent1(url);
        return AjaxResult.success(response);
    }


    @GetMapping("/download1")
	@Inner(value = false)
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response) {
        try {
            byte[] imageByte = portraitsService1.downloadImage(resource);
//            byte[] imageByte = ResourceUtil.readBytes("avatar.png");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-Disposition", "inline; filename=\"avatar.png\"");

            IoUtil.write(response.getOutputStream(), true, imageByte);
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }



    @RequestMapping("/downloadBase64")
    @ResponseBody
    public AjaxResult downloadBase64(String resource) {
        byte[] imageByte = portraitsService1.downloadImage(resource);
        String base64 = Base64.encode(imageByte);
        base64 = "data:image/jpg;base64," + base64;
        return AjaxResult.success(base64);
    }



}
